#include<iostream>
#include<unistd.h>
#include<cstring>
#include<cstdio>

int main()
{
    int Pipefd[2];
    int ret=pipe(Pipefd);
    if(ret!=0){
        std::cerr<<"pipe error"<<std::endl;
        return 1;
    }
    pid_t id=fork();
    if(id<0){
        std::cerr<<"fork error"<<std::endl;
        return 2;
    }
    else if(id==0){
        close(Pipefd[1]);
        char buffer[1024];
        while(true){
            memset(buffer,0,1024);
            ssize_t s=read(Pipefd[0],buffer,sizeof(buffer)-1);
            if(s>0){
                buffer[s]='\0';
                std::cout<<buffer<<std::endl;
            }
            else if(s==0){
                std::cout<<"parent write ending,child read ending!\n"<<std::endl;
                break;
            }
            else{
                return -1;
            }
        }
    }
    else{
        close(Pipefd[0]);
        const char* msg="I am parent process!I send message to you by pipe!message num:: ";
        int cnt=0;
        while(cnt<5){
            char Sendbf[1024];
            sprintf(Sendbf,"%s %d",msg,cnt);
            write(Pipefd[1],Sendbf,strlen(Sendbf));
            sleep(1);
            cnt++;
        }
        std::cout<<":Parent process finished write"<<std::endl;
    }
    return 0;
}
